import requests
from lxml import etree
import os

def fetch_douban_book_details(url):
    # 设置请求头，模拟浏览器访问
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
        'Accept-Language': 'en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7'
    }

    try:
        # 发送HTTP请求
        response = requests.get(url, headers=headers)
        response.raise_for_status()  # 如果响应状态码不是200，抛出异常
    except requests.exceptions.RequestException as e:
        print(f"请求失败: {e}")
        return None

    # 解析HTML内容
    html = response.text
    tree = etree.HTML(html)

    # 提取书名
    title = tree.xpath('//span[@property="v:itemreviewed"]/text()')
    title = title[0].strip() if title else "未知"

    # 提取作者
    author = tree.xpath('//a[@rel="v:author"]/span/text()')
    author = ', '.join(author).strip() if author else "未知"

    # 提取出版社
    publisher = tree.xpath('//span[@class="pl"][contains(text(), "出版社:")]/following-sibling::a/text()')
    publisher = publisher[0].strip() if publisher else "未知"

    # 提取出版年份
    publication_year = tree.xpath('//span[@class="pl"][contains(text(), "出版年:")]/following-sibling::text()')
    publication_year = publication_year[0].strip().replace('/', '').strip() if publication_year else "未知"

    # 提取ISBN
    isbn = tree.xpath('//span[@class="pl"][contains(text(), "ISBN:")]/following-sibling::text()')
    isbn = isbn[0].strip().replace('/', '').strip() if isbn else "未知"

    # 提取简介
    summary = tree.xpath('//div[@class="intro"]//p/text()')
    summary = '\n'.join(summary).strip() if summary else "无简介"

    # 打印提取的信息
    print(f"书名: {title}")
    print(f"作者: {author}")
    print(f"出版社: {publisher}")
    print(f"出版年份: {publication_year}")
    print(f"ISBN: {isbn}")
    print(f"简介: {summary}")

    # 返回提取的信息（可选）
    return {
        'title': title,
        'author': author,
        'publisher': publisher,
        'publication_year': publication_year,
        'isbn': isbn,
        'summary': summary
    }

# 示例使用
if __name__ == "__main__":
    url = 'https://book.douban.com/subject/36743030/'
    book_details = fetch_douban_book_details(url)
    if book_details:
        # 保存到文件
        file_name = f"{book_details['title']}.txt"
        with open(file_name, 'w', encoding='utf-8') as file:
            file.write(f"书名: {book_details['title']}\n")
            file.write(f"作者: {book_details['author']}\n")
            file.write(f"出版社: {book_details['publisher']}\n")
            file.write(f"出版年份: {book_details['publication_year']}\n")
            file.write(f"ISBN: {book_details['isbn']}\n")
            file.write(f"简介: {book_details['summary']}\n")
        print(f"详细信息已保存到 {file_name}")
